using System;
using System.Data;
//using System.Data.SQL;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using  System.Text.RegularExpressions ;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
namespace CStock
{
	/// <summary>
	/// Summary description for WebQuotes.
	/// </summary>
	public class SocketDownload
	{

        public SocketDownload()
		{
			
		}
        private static IPEndPoint CreateIPEndPoint_proxyServer(string proxyServer, int port)
        {
            try
            {
               

                //string host = "mein.proxy.de";
                //int Port = 80;

                IPHostEntry hostEntry = Dns.GetHostEntry(proxyServer); // ip resolven
                IPAddress Address = hostEntry.AddressList[0]; // nimmt die 1. IP ausm Resolve
                IPEndPoint EPhost = new IPEndPoint(Address, port);
                return EPhost;
            }
            catch
            {
                return null;
            }

        }
        private static IPEndPoint CreateIPEndPoint(string server, string portnummer, string post, string uri)
        {
           
            IPHostEntry hostEntry;
            IPAddress[] adresses;
            try
            {

                hostEntry = Dns.GetHostEntry(server);
                string hostName = hostEntry.HostName;
                adresses = hostEntry.AddressList;
                    
            }
            catch (Exception e)
            {
                string str = string.Empty;
                str += "Error in DNS.Resolve of " + server + " \"" + e.Message + "\"";
                str += "server: " + server + " port: " + portnummer + " url: " + uri;
                return null;
            }

          

            Int32 port = 80;
            if (portnummer != null && portnummer != string.Empty)
            {
                try
                {
                    port = Int32.Parse(portnummer);
                }
                catch
                {
                    port = 80;
                }
            }
            IPEndPoint EPhost = new IPEndPoint(adresses[0], port);
            return EPhost;

        }
        private static Byte[] CreateGETArray(string server,string post, string uri)
        {
            Encoding ASCII = Encoding.ASCII;
            String Get, lastString = "\r\n\r\n";
            int iGet;
            if ((iGet = post.Length) > 0)
            {
                Get = "POST ";
                lastString = "Content-Length: " + iGet + lastString + post;
            }
            else
            {
                Get = "GET ";
            }
            Get += uri + " HTTP/1.1\r\n" + "Host: " + server + "\r\n" + "Connection: Close\r\n" + lastString;


            Byte[] ByteGet = ASCII.GetBytes(Get);
            return ByteGet;
        }

        public static string ReceiveBytes(Socket socket, IPEndPoint EPhost, Byte[] GetRequest)
        {
            Encoding ASCII = Encoding.ASCII;
            Byte[] RecvBytes = new Byte[256];
            string strRetPage = string.Empty;
            try
            {
                // Connect to host using IPEndPoint
                socket.Connect(EPhost);

                if (!socket.Connected)
                {
                    strRetPage = "Unable to connect to host";
                    return strRetPage;
                }

                // Send the GET request array to the host
                socket.Send(GetRequest, GetRequest.Length, 0);

                // Receive the page, loop until all bytes are received
                Int32 bytes;
                while ((bytes = socket.Receive(RecvBytes, RecvBytes.Length, 0)) > 0)
                {
                    strRetPage += ASCII.GetString(RecvBytes, 0, bytes);
                }
                //str += "Receive of " + strRetPage.Length.ToString() ;           

                return strRetPage;
            }
            catch (Exception err)
            {
                System.Windows.Forms.MessageBox.Show("Error connecting to internet - Do you have a proxy server? Error is: " + err.Message);
                //Debug.Assert(false,"Error connecting to internet", excep.Message);
                return string.Empty;
            }
            
        }
        //private static IPEndPoint ResolveHostProxy()
        //{
            
        //    IPHostEntry hostEntry = Dns.GetHostEntry(host); // ip resolven
        //    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Socket erstellen
        //    IPAddress Address = hostEntry.AddressList[0]; // nimmt die 1. IP ausm Resolve
        //    IPEndPoint EPhost = new IPEndPoint(Address, Port);

        //    //Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Socket erstellen
            
        //    //socket.Connect(EPhost); // connecten
        //    return EPhost;
        //}
        public static string GetPageFromInternet(string server, string portnummer, string post, string uri)
		{


            //IPEndPoint EPhost = CreateIPEndPoint(server, portnummer, post, uri);
            //string proxyServer = "proxy.erlm.siemens.de";
            //int port = 81;
            //IPEndPoint EPhost = CreateIPEndPoint_proxyServer(proxyServer, port);
            IPEndPoint EPhost = CreateIPEndPoint(server, portnummer, post, uri);
            
            if (EPhost == null)
                return string.Empty;

            string strRetPage = string.Empty;

            //TestSockets();
			//Create the Socket for sending data over TCP
			
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
            Byte[] GetRequest = CreateGETArray(server, post, uri);
            string strReturn = ReceiveBytes(socket, EPhost, GetRequest);
            return strReturn;

		}
        private static Socket TestSockets()
        {
            try
            {
                string host;
                int port = 80;
                host = Dns.GetHostName();


                Socket s = null;
                IPHostEntry hostEntry = null;

                // Get host related information.
                hostEntry = Dns.GetHostEntry(host);

                // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
                // an exception that occurs when the host IP Address is not compatible with the address family
                // (typical in the IPv6 case).
                foreach (IPAddress address in hostEntry.AddressList)
                {
                    IPEndPoint ipe = new IPEndPoint(address, port);
                    Socket tempSocket =
                        new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                    tempSocket.Connect(ipe);

                    if (tempSocket.Connected)
                    {
                        s = tempSocket;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                return s;
            }
            catch (Exception err)
            {
                Debug.Assert(false, "Error connecting to internet : " + err.Message);
                return null;
            }
        }

		/// <summary>
        /// GetInternetPage
		/// </summary>
		/// <param name="dc"></param>
		/// <returns></returns>
		public static string GetInternetPage(string completeURL)
		{
			
			string server, port, uri;
			SocketDownload.ExtractInternetParameters (completeURL, out server, out port, out uri);

			return GetPageFromInternet(server, port,"", uri);
		}
        public static void ExtractInternetParameters(string p_url, out string p_server, out string port, out string uri)
        {
            //http://infomanager3.consors.de:80/consors/formswitch3?searchfor=555750

            Regex regex = new Regex(@"^\w+://(?<1>[^:/]+)(?<2>:\d*)?(?<3>.*)");
            p_server = "";
            port = "";
            uri = "";
            if (regex.IsMatch(p_url))
            {
                p_server = regex.Match(p_url).Result("${1}");
                port = regex.Match(p_url).Result("${2}");
                uri = regex.Match(p_url).Result("${3}");
                regex = new Regex(@":(?<1>.*)");
                if (regex.IsMatch(port))
                {
                    port = regex.Match(port).Result("${1}");
                }
                else
                {

                    //string str = "Port set to 80";
                    port = "80";

                }
            }
        }
        public static string GetQuote(string server, string portnummer,
            string uri, string post)
        {
            return SocketDownload.GetPageFromInternet(server, portnummer, post, uri);
        }
        public static string GetQuote(string server, string portnummer,
            string uri, string post, bool bSavePage, string shareName, string shareID)
        {


            string strRetPage = GetPageFromInternet(server, portnummer, post, uri);

            TextWriter writer = null;
            if (bSavePage)
            {
                try
                {
                    writer = new StreamWriter(shareName + " - " + shareID + ".txt");
                    writer.Write(strRetPage);
                    writer.Close();
                }
                catch
                {
                    if (writer != null)
                        writer.Close();

                    //do nothing
                }
            }

            return strRetPage;
        }



	}
}
